package com.book.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.book.common.annotation.Log;
import com.book.common.annotation.group.InsertGroup;
import com.book.common.annotation.group.UpdateGroup;
import com.book.common.core.controller.BaseController;
import com.book.common.core.domain.AjaxResult;
import com.book.common.core.page.TableDataInfo;
import com.book.common.enums.BusinessType;
import com.book.common.utils.DateUtils;
import com.book.common.utils.StringUtils;
import com.book.system.domain.Book;
import com.book.system.domain.BookCategory;
import com.book.system.domain.BookChapter;
import com.book.system.service.IBookCategoryService;
import com.book.system.service.IBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Bigboss
 * @create 2024-10-20 14:38
 */
@Api(tags = "书籍管理")
@RestController
@RequestMapping("/system/book")
public class SysBookController extends BaseController {

    private final IBookService bookService;
    private final IBookCategoryService bookCategoryService;

    public SysBookController(IBookService bookService, IBookCategoryService bookCategoryService) {
        this.bookService = bookService;
        this.bookCategoryService = bookCategoryService;
    }

    /**
     * 获取书籍列表
     * @return
     */
    @ApiOperation(value = "书籍列表，权限：system:book:list")
    @PreAuthorize("@ss.hasPermi('system:book:list')")
    @GetMapping("/list")
    public TableDataInfo list(Book book)
    {
        startPage();
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>().orderByAsc(Book::getCreateTime);
        if(StringUtils.isNotEmpty(book.getBookName())){
            queryWrapper.like(Book::getBookName,book.getBookName());
        }
        List<Book> list = bookService.list(queryWrapper);
        if(ObjectUtil.isNotEmpty(list)){
            List<String> categoryIds = list.stream().map(Book::getCategoryId).distinct().collect(Collectors.toList());
            List<BookCategory> bookCategories = bookCategoryService.listByIds(categoryIds);
            //bookCategories通过id分组，每个id只会有一个元素
            Map<String, BookCategory> categoryMap = bookCategories.stream().collect(Collectors.toMap(BookCategory::getId, Function.identity()));
            list.stream().forEach(item -> item.setCategory(categoryMap.getOrDefault(item.getCategoryId(),null)));
        }
        return getDataTable(list);
    }


    /**
     * 新增书籍
     */
    @ApiOperation(value = "新增书籍，权限：system:book:add")
    @PreAuthorize("@ss.hasPermi('system:book:add')")
    @Log(title = "书籍管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated({InsertGroup.class}) @RequestBody Book entity)
    {

        entity.setCreateBy(getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return toAjax(bookService.save(entity));
    }

    /**
     * 修改书籍
     */
    @ApiOperation(value = "修改书籍，权限：system:book:edit")
    @PreAuthorize("@ss.hasPermi('system:book:edit')")
    @Log(title = "书籍管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated({UpdateGroup.class}) @RequestBody Book entity)
    {
        entity.setUpdateBy(getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return toAjax(bookService.updateById(entity));
    }


    /**
     * 书籍更新完结
     * @param bookId
     * @return
     */
    @ApiOperation(value = "书籍更新完结，权限：system:book:edit")
    @PreAuthorize("@ss.hasPermi('system:book:edit')")
    @Log(title = "书籍管理（完结）", businessType = BusinessType.UPDATE)
    @PutMapping("/end/{bookId}")
    public AjaxResult end(@PathVariable String bookId)
    {
        Book book = new Book();
        book.setId(bookId);
        book.setStatus("2");
        book.setEndTime(DateUtils.getNowDate());
        return toAjax(bookService.updateById(book));
    }


    /**
     * 更新书籍章节
     * @param chapter
     * @return
     */
    @ApiOperation(value = "更新书籍章节，权限：system:book:edit")
    @PreAuthorize("@ss.hasPermi('system:book:edit')")
    @Log(title = "书籍管理", businessType = BusinessType.UPDATE)
    @PostMapping("/addChapter")
    public AjaxResult addChapter(@RequestBody @Validated BookChapter chapter){
        //查询书籍是否存在或书籍是否完结
        Book book = bookService.getById(chapter.getBookId());
        if(ObjectUtil.isNull(book) || book.getStatus().equals("2")){
            return error("书籍不存在或书籍已完结");
        }
        chapter.setChapter(book.getChapter()+1);
        chapter.setCreateBy(getUsername());
        chapter.setCreateTime(DateUtils.getNowDate());
        return toAjax(bookService.addChapter(chapter));
    }


    /**
     * 查询书籍的所有章节
     * @param bookId
     * @return
     */
    @ApiOperation(value = "查询书籍的所有章节，权限：system:book:edit")
    @PreAuthorize("@ss.hasPermi('system:book:edit')")
    @GetMapping("/getAllChapters/{bookId}")
    public AjaxResult getAllChapters(@PathVariable String bookId){
        return success(bookService.getAllChapters(bookId));
    }


    /**
     * 删除书籍
     */
    @ApiOperation(value = "删除书籍，权限：system:book:remove")
    @PreAuthorize("@ss.hasPermi('system:book:remove')")
    @Log(title = "书籍管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        return toAjax(bookService.removeById(id));
    }

}
